<template>
  <div class="customer-pool">
    <page-box>
      <template #search>
        <search-form :fieldList="fieldList" :form="form" @onSearchFun="searchFun"></search-form>
      </template>
      <template #btn>
        <el-button @click="searchFun">查询</el-button>
        <advanced-search
          ref="customSearch"
          :searchType="isAdvanced"
          :conditionList="conditionList"
          :fieldList="fieldListSearch"
          :fieldSelectList="fieldSelectList"
          :customList="customList"
          @onDeleteCustomClick="deleteCustomClick"
          @onSaveCondition="saveConditionFun"
          @onSearchFun="handleSearch"
        ></advanced-search>
        <el-button @click="addCusFun" type="primary">新建</el-button>
      </template>
      <template #table>
        <resize-table
          ref="tableRef"
          v-loading="loading"
          :headers="tableHeaders"
          :data="tableData"
          :pagingData="pagingData"
          @onPageChange="handleCurrentChange"
          @onPageSizeChange="handleSizeChange"
          :showPagination="true"
          :selection="true"
          :headersConfig="true"
          @onCheckHeadersChange="checkHeadersChange"
          :batchs="batchs"
          @onBatchClick="batchClick"
          :dynamic="true"
        >
          <!-- 附件 -->
          <template #attachments="{ scope }">
            <span v-for="(attachmentItem, index) in scope.row.attachments" :key="index" class="attachment">
              <a :href="attachmentItem.url" target="_blank" download>{{
                attachmentItem.fileName + (index === scope.row.attachments.length - 1 ? ' ' : '、 ')
              }}</a>
            </span>
          </template>
          <template #serviceLabel="{ scope }">
            <el-tag
              v-for="(item, index) in scope.row.serviceLabel"
              :key="index"
              :color="item.color"
              :style="{
                color: item.color === '#FFFFFF' || item.color === '#fff' || !item.color ? '#252c32' : '#ffffff'
              }"
            >
              <el-tooltip :content="item.name" placement="top" effect="light">
                {{ item.name }}
              </el-tooltip>
            </el-tag>
          </template>
          <!-- 操作 -->
          <template #oprate="{ scope }">
            <span class="btn" @click="toDetail(scope.row)">详情</span>
            <span class="btn" @click="delCusFun(scope.row)">删除</span>
          </template>
        </resize-table>
      </template>
    </page-box>
    <!-- 新建客户 -->
    <resize-drawer
      :title="drawer.title"
      :drawer="drawer.show"
      :size="576"
      :isShowMoreBtn="true"
      @onSave="saveFun"
      @onCloseDraw="closeDraw"
      @onCancelFun="closeDraw"
    >
      <template #column>
        <add-customer ref="addCustomerRef" :form="addForm"></add-customer>
      </template>
    </resize-drawer>
    <!-- 详情 -->
    <customer-detail ref="customerDetailRef" @onUpdateData="searchType"></customer-detail>
    <!-- 分配 -->
    <distribute-cus ref="distributeCustomer" @onClearBatchSelect="clearBatchSelect" :noBtn="true"></distribute-cus>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, getCurrentInstance, markRaw, nextTick, onMounted, reactive, toRefs } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import distributeCus from '@app/customer/components/distribute/dialog-distribute.vue'
import {
  batchDel,
  cusDetail,
  cusList,
  delCus,
  addCus,
  getHeader,
  updateHeader,
  getAdvanced,
  delAdvanced,
  addAdvanced,
  advancedList
} from '@app/customer/apis/pool'
import searchForm from '@/common/components/base-form/form.vue'
import resizeTable from '@/common/components/resize-table/index.vue'
import resizeDrawer from '@/common/components/resize-drawer/index.vue'
import addCustomer from './components/add-customer.vue'
import customerDetail from './components/customer-detail/index.vue'
import pageBox from '@common/components/page-box.vue'
import advancedSearch from '@common/components/advanced-search/index.vue'
import { deepClone } from '@/common/utils/common'
import { showFieldObj } from '@app/customer/mixins/index'
import mcCache from '@/common/utils/mc-get-cache'
import { commonStore } from '@/common/store/modules/common'
import { getGender, createMethodsOption } from '@app/customer/utils/common'
import { encryptPhone } from '@/common/utils/common'
import deleteIcon from '@/common/components/delete-icon/index.vue'
interface State {
  fieldList: Record<string, unknown>[]
  form: Record<string, unknown>
  tableHeaders: Record<string, unknown>[]
  tableData: Record<string, unknown>[]
  pagingData: Record<string, number>
  batchs: Record<string, unknown>[]
  drawer: Record<string, unknown>
  addForm: Record<string, unknown>
  detailData: Record<string, unknown>
  conditionList: any
  fieldSelectList: any
  fieldListSearch: Record<string, unknown>[]
  customList: Record<string, unknown>[]
  isAdvanced: boolean
  advancedObj: Record<string, unknown>
  loading: boolean
}
export default defineComponent({
  name: 'customerPool',
  components: {
    searchForm,
    resizeTable,
    resizeDrawer,
    addCustomer,
    customerDetail,
    pageBox,
    advancedSearch,
    distributeCus
  },
  setup() {
    const instance: any = getCurrentInstance()

    const state: State = reactive({
      fieldList: [
        {
          name: '客户名称',
          field: 'customerName',
          type: 'text'
        },
        {
          name: '手机号码',
          field: 'mobile',
          type: 'text'
        }
      ],
      form: {
        customerName: '',
        mobile: ''
      },
      tableHeaders: [],
      tableData: [],
      pagingData: {
        page: 1,
        total: 0,
        limit: 10
      },
      batchs: [
        {
          name: '批量分配',
          action: 'distribute',
          _id: 'customer_assign'
        },
        {
          name: '批量删除',
          action: 'delete',
          _id: 'customer_delete'
        }
      ],
      drawer: {
        title: '新建客户',
        show: false
      },
      addForm: {
        createMethod: 'INSERT'
      },
      detailData: {}, // 详情数据
      conditionList: {}, // 高级搜索类型及条件
      fieldSelectList: {}, // 高级搜索选项
      customList: [], // 常用检索
      fieldListSearch: [], // 高级搜索字段
      isAdvanced: false, // 高级检索 普通搜索区分标识
      advancedObj: {}, // 高级搜索参数
      loading: true
    })

    const globalFieldsObj: any = computed(() => {
      // 获取全局字段obj
      return commonStore().publicCache.globalFieldCacheObj || {}
    })

    const cusInfoObj: any = computed(() => {
      // 客户信息obj
      return commonStore().publicCache.cusInfoObj || {}
    })

    const region: any = computed(() => {
      // 地区
      return commonStore().publicCache.region || []
    })

    const serviceLabels: any = computed(() => {
      // 服务标签
      return commonStore().publicCache.serviceLabels || []
    })

    const userList: any = computed(() => {
      // 员工
      return commonStore().publicCache.userCache || []
    })

    const save = (formData: any) => {
      addCus(formData).then((res) => {
        if (res.success) {
          state.drawer.show = false
          ElMessage.success('操作成功')
          state.form = {} // 清空搜索数据
          searchFun()
        }
      })
    }

    const saveFun = () => {
      // 保存
      const disData = instance?.refs.addCustomerRef.checkDisForm()
      const data = instance?.refs.addCustomerRef.checkForm()
      Promise.all([disData, data]).then(([res1, res2]: any) => {
        if (res1 && res1.status && res2.status) {
          save({ ...res1.form, ...res2.form })
        } else if (!res1 && res2.status) {
          save(res2.form)
        }
      })
    }

    const getDetail = async (id: string) => {
      const res = await cusDetail(id)
      if (res.success) {
        Object.keys(res.data).forEach((v) => {
          if (v === 'mobile' && res.data[v] && res.data[v].length) {
            res.data[v].forEach((i: any) => {
              i.bakValue = i.value // 未隐藏的号码
              i.value = encryptPhone(i.value)
            })
          }
        })
        state.detailData = res.data
      }
    }

    const toDetail = async (row: any) => {
      // 详情
      await getDetail(row._id)
      instance?.refs.customerDetailRef.openDetail(state.detailData)
    }

    const delCusFun = (row: any) => {
      ElMessageBox.confirm('删除后数据无法恢复，请确认是否删除?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        icon: markRaw(deleteIcon)
      }).then(() => {
        delCus({ id: row._id }).then((res) => {
          if (res.success) {
            ElMessage.success('删除成功')
            searchFun()
          }
        })
      })
    }

    const checkHeadersChange = (checkList: any, init: boolean) => {
      if (init) {
        return
      }
      state.tableHeaders = checkList || []
      updateHeaderConfig()
    }

    // 批量操作
    const batchClick = (action: string, selectList: any) => {
      let ids = []
      let condition = {}
      if (selectList === true) {
        // 全选
        ids = []
        condition = { search: getParams(state.form) }
      } else {
        // 部分选中
        ids = selectList
        condition = {}
      }
      switch (action) {
        case 'distribute':
          batchDistrubute(ids, condition)
          break
        case 'delete':
          batchDelete(ids, condition)
          break
      }
    }

    // 批量分配
    const batchDistrubute = (ids: [], condition: any) => {
      instance?.refs.distributeCustomer.openDialog(ids, condition, true)
    }

    // 批量删除
    const batchDelete = (ids: any = [], condition = {}) => {
      ElMessageBox.confirm('确定要批量删除客户吗', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        icon: markRaw(deleteIcon)
      }).then(() => {
        batchDel({
          ids,
          condition
        }).then((res) => {
          if (res.success) {
            ElMessage.success('操作成功')
            clearBatchSelect()
          }
        })
      })
    }

    // 清空操作栏
    const clearBatchSelect = () => {
      instance?.refs.tableRef.cancelSelectFun()
      searchType()
    }

    const handleCurrentChange = (page: number) => {
      state.pagingData.page = page
      searchType()
    }

    const handleSizeChange = (size: number) => {
      state.pagingData.limit = size
      searchType()
    }

    // 搜索
    const searchFun = () => {
      state.isAdvanced = false
      searchType(true)
    }

    const searchType = (init?: boolean) => {
      if (init) {
        state.pagingData.page = 1
      }
      if (state.isAdvanced) {
        // 高级搜索
        getList('advanced', state.advancedObj)
      } else {
        // 普通搜索
        getList('', {})
      }
    }

    // 新建客户
    const addCusFun = async () => {
      state.drawer.show = true // 展开抽屉
      state.addForm = { createMethod: 'INSERT' } // 清空数据
    }

    const closeDraw = () => {
      state.drawer.show = false // 关闭抽屉
    }

    // 处理参数
    const getParams = (form: any) => {
      const arr: any = [] // 存储
      const arr2 = Object.keys(form) // state.form对应的数组
      if (arr2 && arr2.length) {
        arr2.forEach((item) => {
          if (state.form[item]) {
            arr.push({
              field: item,
              value: [state.form[item]],
              operator: 'eq'
            })
          }
        })
      }
      return arr
    }

    // 获取字段
    const getList = (type: string, obj: any) => {
      const sendData: any = {
        limit: state.pagingData.limit,
        page: state.pagingData.page
      }
      if (type) {
        sendData.conditions = obj.advanceQuery || []
        sendData.id = obj.id || ''
      } else {
        sendData.search = getParams(state.form)
      }
      ;(type ? advancedList(sendData) : cusList(sendData)).then((res: any) => {
        if (res.success && res.data) {
          state.tableData = handleTableList(res.data.list) || []
          state.pagingData.total = res.data.count || 0
        }
      })
    }

    const handleTableList = (tablelist: any) => {
      tablelist.map((item: any) => {
        Object.keys(item).forEach((keyItem) => {
          const fieldObj = globalFieldsObj.value[keyItem] || {}
          showFieldObj(fieldObj, keyItem, item) // 展示处理
        })
      })
      return tablelist
    }

    // 获取表头
    const getHeaderConfig = () => {
      getHeader().then((res) => {
        if (res.success && res.data) {
          state.loading = false
          res.data.headers.forEach((item: any) => {
            if (['attachments', 'serviceLabel'].includes(item.prop)) {
              // 附件自定义
              item.custom = true
            }
          })
          state.fieldListSearch = res.data.headers.filter((v: any) => v.prop !== 'attachments')
          handleAdvancedSearch(res.data.headers) // 获取高级搜索(除操作记录)
          res.data.headers.push({ label: '操作', prop: 'oprate', show: true })
          state.tableHeaders = res.data.headers
        }
      })
    }

    const getCondition = (type: string) => {
      // 根据字段type获取高级搜索类型和条件
      switch (type) {
        case 'text':
          return { type: 'string', condition: ['eq'] }
        case 'multi-text':
          return { type: 'string', condition: ['eq'] }
        case 'pairs':
          return { type: 'string', condition: ['eq'] }
        case 'cascade':
          return {
            type: 'cascader',
            condition: ['eq', 'neq', 'empty', 'nempty'],
            props: { value: 'key', label: 'value', children: 'children' }
          }
        case 'datetime':
          return { type: 'date', condition: ['eq', 'gte', 'lte', 'between'] }
        case 'datetime-range':
          return { type: 'date', condition: ['eq', 'gte', 'lte', 'between'] }
        case 'number':
          return { type: 'number', condition: ['eq', 'gte', 'lte', 'between'] }
        case 'radio':
          return {
            type: 'select',
            condition: ['eq', 'neq', 'in', 'nin', 'empty', 'nempty'],
            props: { label: 'value', value: 'key' }
          }
        case 'multi-select':
          return {
            type: 'select',
            condition: ['eq', 'neq', 'in', 'nin', 'empty', 'nempty'],
            props: { label: 'value', value: 'key' }
          }
      }
    }

    const handleAdvancedSearch = (data: any) => {
      if (data && data.length) {
        state.conditionList = {} // 清空数据
        state.fieldSelectList = {}
        data.forEach((i: any) => {
          const fieldObj = cusInfoObj.value[i.prop] // 客户信息里面的字段信息
          if (fieldObj) {
            if (!['attachments', 'region', 'serviceLabel'].includes(fieldObj.field)) {
              state.conditionList[i.prop] = getCondition(fieldObj.type)
            } else if (fieldObj.field === 'region') {
              state.conditionList.region = {
                type: 'cascader',
                condition: ['eq', 'neq', 'empty', 'nempty'],
                props: { value: 'id', label: 'fullname', children: 'children' }
              }
            } else if (fieldObj.field === 'serviceLabel') {
              state.conditionList.serviceLabel = {
                type: 'cascader',
                condition: ['eq', 'neq', 'empty', 'nempty'],
                props: { value: '_id', label: 'name', children: 'children' }
              }
            }
            // 选项处理
            const gloFieldObj = globalFieldsObj.value[i.prop]
            if (['radio', 'multi-select', 'cascade'].includes(fieldObj.type)) {
              if (i.prop === 'region') {
                // 省市区
                state.fieldSelectList.region = region.value
              } else if (i.prop === 'gender') {
                // 性别
                state.fieldSelectList.gender =
                  gloFieldObj &&
                  gloFieldObj.choices.map((v: any) => {
                    return {
                      key: v.key,
                      value: getGender[v.key]
                    }
                  })
              } else if (
                ['lastCallUser', 'lastChatUser', 'updateAgent', 'createAgent', 'firstOwner', 'owner'].includes(i.prop)
              ) {
                state.fieldSelectList[i.prop] = userList.value.map((v: any) => {
                  return {
                    key: v._id,
                    value: v.agentName + '[' + v.agentNumber + ']'
                  }
                })
              } else if (i.prop === 'serviceLabel') {
                // 服务标签
                state.fieldSelectList.serviceLabel = serviceLabels.value
              } else if (i.prop === 'createMethod') {
                state.fieldSelectList.createMethod = createMethodsOption
              } else {
                // 其他
                state.fieldSelectList[i.prop] =
                  fieldObj.type === 'cascade'
                    ? (gloFieldObj && gloFieldObj.options && gloFieldObj.options.children) || []
                    : (gloFieldObj && gloFieldObj.choices) || []
              }
            }
          }
        })
      }
    }

    const saveConditionFun = (obj: any) => {
      //  高级搜索-保存常用检索
      addAdvanced({
        conditions: obj.advanceQuery,
        name: obj.name,
        id: obj.currentCustomId
      }).then((res) => {
        if (res.success) {
          ElMessage.success('操作成功')
          getConditionFun()
        }
      })
    }

    const getConditionFun = () => {
      // 高级搜索-获取常用检索
      getAdvanced({}).then((res) => {
        if (res.success) {
          state.customList = res.data || []
        }
      })
    }

    const deleteCustomClick = (row: any) => {
      // 删除常用检索
      delAdvanced({ _id: row._id }).then((res) => {
        if (res.success) {
          ElMessage.success('操作成功')
          getConditionFun()
        }
      })
    }

    const handleSearch = (obj: any) => {
      // 高级检索
      state.isAdvanced = true
      state.advancedObj = obj
      instance?.refs.customSearch.hidePopover()
      searchType(true)
    }

    // 更新表头
    const updateHeaderConfig = () => {
      const headers = deepClone(state.tableHeaders)
      headers.splice(headers.length - 1, 1) // 去掉操作
      updateHeader({ headers }) // 更新表头数据
    }

    onMounted(async () => {
      await mcCache.$getCache('globalFieldCache', 'hasObj', '', '', '', '', 'field') // 全局字段
      await mcCache.$getCache('cusInfo', 'hasObj', '', '', '', '', 'field') // 客户信息
      await mcCache.$getCache('region') // 地区
      await mcCache.$getCache('serviceLabels') // 服务标签
      await getHeaderConfig() // 表头
      getList('', {}) // 非高级搜索列表
      getConditionFun() // 高级搜索-常用检索
    })

    return {
      ...toRefs(state),
      closeDraw,
      addCusFun,
      searchFun,
      handleSizeChange,
      handleCurrentChange,
      clearBatchSelect,
      batchClick,
      checkHeadersChange,
      delCusFun,
      toDetail,
      saveFun,
      deleteCustomClick,
      saveConditionFun,
      handleSearch,
      searchType
    }
  }
})
</script>

<style lang="stylus" scoped>
.customer-pool
  .btn
    color var(--mc-main-color)
    cursor pointer
    margin-right 16px
    &:last-child
      margin-right 0px
</style>
